package com.qianbao.finance.sync.modules.elasticsearch.websocket.simulator;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import com.qianbao.finance.sync.common.utils.SpringContextUtils;
import com.qianbao.finance.sync.modules.elasticsearch.websocket.server.ShareConfig;
import com.qianbao.finance.sync.modules.elasticsearch.websocket.utils.CByteDecoder;
import org.apache.log4j.Logger;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;




/**
 * 接收Zabbix Agent监控数据Socket服务端 将监控数据整理发送前端监控的Socket客户端
 * 
 * @author WangYuan
 * @date 2016年7月23日下午3:47:18
 */
public class ZBXServerSimulator implements Runnable {

    private static final Logger logger = Logger.getLogger(ZBXServerSimulator.class);

    private static ShareConfig shareConfig = (ShareConfig) SpringContextUtils.getBean("shareConfig");
    @Override
    public void run() {

        int port = shareConfig.getSimulatorPort();

        ChannelFactory factory =
                new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
                        Executors.newCachedThreadPool());

        ServerBootstrap bootstrap = new ServerBootstrap(factory);
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() {
                return Channels.pipeline(new CByteDecoder(), new SimulatorHandler());
            }
        });

        bootstrap.setOption("child.keepAlive", true);
        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.bind(new InetSocketAddress(port));

        logger.info(String.format("ZBXServerSimulator has been bind %s and start up ...", port));
    }

}
